package com.ymttest.utils;

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.XMLWriter;
import org.junit.runner.Result;

import com.ymatou.ResultParser;
import com.ymatou.database.Wapper.TestCaseWapper;
import com.ymt.core.tool.Logger;

public class SelectCaseRun {
	
	
	public static void main(String[] args) throws Exception {
		insertResult("productprice.iapi.ymatou.com");
		
	}
	
	
	
	public static void addUrl(String domain){
		File resultFile = new File(RESULT_PATH);
		File[] fileList = resultFile.listFiles();
		for(File file:fileList){
			if (!file.isFile()&&file.getName().equals(domain)){
				File[] caseFileList = file.listFiles();
				for(File caseFile:caseFileList){
					if (!caseFile.isFile()){
						String urlName = caseFile.getName();
						File[] resultCaseList = caseFile.listFiles();
						for(File resultCase : resultCaseList){
							if (resultCase.isFile() && resultCase.length()>0){
								try{
									Document document = DocumentHelper.parseText(FileUtil.readFile(resultCase.getPath()));
									document.getRootElement().addAttribute("url", urlName);
									XMLWriter writer = new XMLWriter(new FileWriter(resultCase.getPath()));
								    writer.write(document);
								    writer.close();
								}catch(Exception e){
									e.printStackTrace();
								}
							}
						}
					}
				}
			}
		}
		
		
		
		
		
	}
	
	
	public static void insertResult(String domain){
		addUrl(domain);
		
		ResultParser resultParser = new ResultParser();
		TestCaseWapper tcw = new TestCaseWapper();

		resultParser.setPath(RESULT_PATH);

		//执行的批次号
		try {
			resultParser.parserXmlToDb(tcw, "SIT1", domain);
			System.out.println("finish");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Logger.info("首次解析结果文件入库失败!"+e.getMessage());		
			e.printStackTrace();	
		}
	}
	
	public static  void selectTestRun(String domain, Map<String, List<String>>TestSuitNameAndCaseListMap,boolean isshuffle){
		List<TestSuiteBean> junitTestCaseList = SelectCaseRun.getTestMethods(domain,TestSuitNameAndCaseListMap);
		
		RunTests.Run(junitTestCaseList,isshuffle);
		
		
		
		ResultParser resultParser = new ResultParser();
		TestCaseWapper tcw = new TestCaseWapper();

		// 设置结果文件路径
		resultParser.setPath(RESULT_PATH);

		//执行的批次号
		int passid=0;
		try {
			passid = resultParser.parserXmlToDb(tcw, "SIT1", domain);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Logger.info("首次解析结果文件入库失败!"+e.getMessage());		
			e.printStackTrace();	
		}
	}
	
	
	
	
	private static int threadNum = 1;

	private static ExecutorService SERVICE;

	private static List<Result> RESULTS = new ArrayList<Result>();
	
	private static String RESULT_PATH = new File("").getAbsolutePath()
			+ File.separator + "Results";
	
	public static List<Result> Run(List<TestSuiteBean> testCaseList) {
		// 删除结果xml 文件
		deleteResultFile(new File(RESULT_PATH));
		// 打乱用例的执行的顺序，尽量避免同一个接口下多个用例同时并发执行
		Collections.shuffle(testCaseList);
		
		if (SERVICE == null || SERVICE.isShutdown()) {
			SERVICE = Executors.newFixedThreadPool(threadNum);
		}
		CountDownLatch countDownLatch = new CountDownLatch(testCaseList.size());
		for (TestSuiteBean testSuiteBean : testCaseList) {
			
			Class junitClass =testSuiteBean.getTestSuiteClass();
			String methodName = testSuiteBean.getTestCaseName();
			
			SERVICE.execute(() -> {
				
				Result r = RunTests.RunCase(junitClass,methodName);
				//    @Ignore 的case 执行返回结果为null，排除掉
				if (r!=null){
					RESULTS.add(r);
				}
				countDownLatch.countDown();
			});
		}
		try {
			// 等待线程池里所有线程任务结束
			countDownLatch.await();
		} catch (Exception e) {
			// TODO: handle exception
			Logger.info("运行error:"+e.getStackTrace());
		}
		return RESULTS;
	}
	
	public static List<TestSuiteBean> getTestMethods(String domain, Map<String, List<String>>TestSuitNameAndCaseListMap) {
		
		List<TestSuiteBean> junitCaseList = new java.util.LinkedList<TestSuiteBean>();
		
		String path = "";
		String[] tempp = null;
		tempp = domain.split("\\.");
		for (String tp : tempp) {
			path = tp + File.separator + path;
		}
		path = System.getProperty("user.dir") + File.separator + "bin"
				+ File.separator + path.substring(0, path.length())
				+ "testcase";
		
		List<String> fileList = TestDataManager.getFilelist(path);
		
		
		
		TestSuitNameAndCaseListMap.forEach((TestSuitName,caseNameList)->{
			String fname = fileList.stream().filter(ele->ele.contains(TestSuitName)).findFirst().orElse("");
			if (!fname.equals("")){
				Class<?> cls = null;
				try {
					cls = TestDataManager.getClassNameByFileName(fname);
				} catch (Exception e) {
					Logger.debug(fname + ":不是一个java class,不处理！");
					e.printStackTrace();
				}
				
				if (cls != null) {
					Method[] ms = cls.getDeclaredMethods();
					
					
						for (Method m1 : ms) {	
							if (caseNameList==null || caseNameList.size()==0){
								TestSuiteBean testSuiteBean=new TestSuiteBean();
								testSuiteBean.setTestSuiteClass(cls);
								testSuiteBean.setTestCaseName(m1.getName());
								junitCaseList.add(testSuiteBean);
								
							}else if (caseNameList.contains(m1.getName()))  {
								TestSuiteBean testSuiteBean=new TestSuiteBean();
								testSuiteBean.setTestSuiteClass(cls);
								testSuiteBean.setTestCaseName(m1.getName());
								junitCaseList.add(testSuiteBean);
							}
						}
					
				}
				
			}
		});
		return junitCaseList;
	}
	
	
	private static void deleteResultFile(File file) {
		if (file.isDirectory()) {
			File[] temp = file.listFiles();
			for (File f : temp) {
				deleteResultFile(f);
			}
		}
		file.delete();
	}
}
